package com.ynding;

import java.awt.*;

/**
 * <p> 钻井工人 </p>
 *
 * @author ynding
 * @version 2021/4/14
 **/
public class JackhammerDuke extends java.applet.Applet implements Runnable {
    int seqslot = 0;//当前循环的片断
    int nimgs = 4;//图片数量
    Image imgs;//Image对象
    String dir;//上载图片路径
    Thread kicker = null;//线程
    int pause;//停顿间隔
    double x;//当前位置
    int imgsWidth = 328;
    int imgsHeight = 90;

    //run()方法，负责循环播放图片，由线程调用
    public void run() {
        //设置线程优先权
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
        //获取图片
        imgs = getImage(getCodeBase(), "images/jack.gif");
        //如果有图片，开始循环播放
        if (imgs != null) {
            x = (size().width - imgsWidth / nimgs) / 2;
            while (size().width > 0 && size().height > 0 && kicker != null) {
                if (seqslot == 0) {
                    play(getCodeBase(), "audio/jackhammer-short.au");
                }
                repaint();
                try {
                    Thread.sleep((seqslot == sequence.length - 1) ? 500 : 100);
                } catch (InterruptedException e) {
                }
                seqslot = (seqslot + 1) % sequence.length;
            }
        }
    }

    //定义图片播放顺序
    private int sequence[] = {2, 1, 0, 1, 0, 1, 0, 1, 2, 1, 0, 2, 0, 1, 0, 2, 3};
    //画当前帧
    boolean erase;

    //update()方法，调用paint()方法
    @Override
    public void update(Graphics g) {
        if (erase || (sequence[seqslot] == 3)) {
            g.setColor(Color.white);
            g.fillRect(0, 0, size().width, size().height);
            erase = false;
        }
        paint(g);
    }

    //paint()方法，负责在屏幕上绘制图像
    @Override
    public void paint(Graphics g) {
        int loopslot = sequence[seqslot];
        if ((imgs != null) && (loopslot < nimgs)) {
            int w = imgsWidth / nimgs;
            x = Math.max(0, Math.min(size().width - w, x + Math.random() * 4 - 2));
            g.clipRect((int) x, 0, w, imgsHeight);
            g.drawImage(imgs, (int) x - loopslot * w, 0, this);
            erase = (loopslot == 3);
        }
    }

    //启动线程
    @Override
    public void start() {
        if (kicker == null) {
            kicker = new Thread(this);
            kicker.start();
        }
    }

    //停止线程
    @Override
    public void stop() {
        kicker = null;
    }
}

